package com.hdl.school.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.IBinder;
import android.os.StatFs;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.RoomEventAction;
import com.hdl.school.bean.SignInInfo;
import com.hdl.school.utils.Config;
import com.hdl.school.utils.TimeUtil;
import com.leectrl.utils.DbUtil;
import com.likong.iotsdk.DeviceType;
import com.likong.iotsdk.RoomInfo;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.SqlInfo;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.db.table.DbModel;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * This Service is Persistent Service. Do some what you want to do here.<br/>
 * <p>
 * Created by Mars on 12/24/15.
 */
public class TaskService extends Service {


    private DbManager db;
    private  int roomId;
    private String serverConfig=null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //TODO do some thing what you want..
        try {
            db=x.getDb(MyApplication.getAppContext().getDaoConfig());
        } catch (DbException e) {
            e.printStackTrace();
        }
        SharedPreferences sharedPreferences=getSharedPreferences("school_iot",0);
        serverConfig=sharedPreferences.getString("serverConfig",null);
        String room=sharedPreferences.getString("room_info",null);
        if(room!=null){
            RoomInfo roomInfo=JSONObject.parseObject(room,RoomInfo.class);
            roomId=roomInfo.getRoomId();
        }

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Date date = TimeUtil.getCurTimeToDate();
                if (date.getHours() == 23 && date.getMinutes() == 0 && date.getSeconds() <= 20) {
                    clearStorage();
                } else {
                   //上传事件
                    uploadEventLog();
                    uploadSignInfo();
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 0, 60000);

    }

    /**
     * 清理存储空间
     */
    private void clearStorage() {
        while (getAvailaleSize() < 2 * 1024 * 1204) {
            File f = new File(Config.FTP_DOWNLOADDIR);
            File[] files = f.listFiles();
            long last = 0;
            int index = 0;
            for (int i = 0; i < files.length; i++) {
                if (last == 0 || files[i].lastModified() < last) {
                    last = files[i].lastModified();
                    index = i;
                }
            }
            files[index].delete();
        }
    }


    private void uploadEventLog() {
        if (db != null&&serverConfig!=null&&roomId>0) {
            try {
                List<DbModel> dbModelList = db.findDbModelAll(new SqlInfo("select * from event_log where upload_tag=0"));
                if(dbModelList==null){
                    return  ;
                }
                String url = "http://" + serverConfig + "/publicapi/terminal/event/log/upload";
                RequestParams requestParams = new RequestParams(url);
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("room_id", roomId);
                jsonObject.put("dev_id", DeviceType.DEVICETYPE_TERMINAL_ANDROID.getDeviceType());
                JSONArray records=new JSONArray();
                for(DbModel dbModel:dbModelList){
                    JSONObject item=new JSONObject();
                    item.put("action",dbModel.getString("action"));
                    item.put("card_num",dbModel.getString("card_num"));
                    item.put("tag",dbModel.getString("tag"));
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put("event_time",formatter.format(dbModel.getDate("event_time",0)));
                    item.put("auth_result",dbModel.getInt("auth_result",1));
                    records.add(item);
                }
                jsonObject.put("records",records);
                requestParams.setBodyContent(JSON.toJSONString(jsonObject));
                x.http().post(requestParams, new Callback.CommonCallback<String>(){

                    @Override
                    public void onSuccess(String result) {
                        JSONObject resultObj=JSON.parseObject(result);
                        if(resultObj.getIntValue("code")==0){
                            JSONArray tags=resultObj.getJSONArray("data");
                            try {
                                KeyValue keyValue=new KeyValue("upload_tag",1);
                                DbUtil.getInstance().update(RoomEventAction.class, WhereBuilder.b("tag","in",tags.toArray()),keyValue);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadSignInfo() {
        if (db != null&&serverConfig!=null&&roomId>0) {
            try {
                List<SignInInfo> signInInfos = db.selector(SignInInfo.class).where("upload_tag","=",0).limit(5).findAll();
                if(signInInfos==null){
                    return  ;
                }
                String url = "http://" + serverConfig + "/publicapi/terminal/sign/info/upload";
                RequestParams requestParams = new RequestParams(url);
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("room_id",roomId);
                jsonObject.put("records",signInInfos);
                System.out.println(JSON.toJSONString(jsonObject));
                requestParams.setBodyContent(JSON.toJSONString(jsonObject));
                requestParams.setConnectTimeout(30000);
                x.http().post(requestParams, new Callback.CommonCallback<String>(){

                    @Override
                    public void onSuccess(String result) {
                        JSONObject resultObj=JSON.parseObject(result);
                        if(resultObj.getIntValue("code")==0){
                            JSONArray tags=resultObj.getJSONArray("data");
                            try {
                                for(int k=0;k<tags.size();k++){
                                    KeyValue keyValue=new KeyValue("upload_tag",1);
                                    DbUtil.getInstance().update(SignInInfo.class, WhereBuilder.b("id_tag","=",tags.getString(k)),keyValue);
                                }
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        System.out.println("ttt:"+ex.getMessage());
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    }


    public long getAvailaleSize() {
        File path = Environment.getExternalStorageDirectory(); //取得sdcard文件路径
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


}
